//
//  ZPayViewController.m
//  shopSN
//
//  Created by chang on 16/7/2.
//  Copyright © 2016年 yisu. All rights reserved.
//

#import "ZPayViewController.h"

#import "ZReceiveAddressViewController.h" //选择收货地址页面

//subView
#import "ZPayConsigneeInfoCell.h"//发货人信息
#import "ZPayTypeCell.h"         //支付选择
#import "ZPayOrderInfoCell.h"   //商品订单信息
#import "ZPayPointsCell.h"      //积分
#import "ZPayMoney.h" //支付
#import "WXApi.h"
enum{
    ApointTag = 100,
    BpointTag
};

@interface ZPayViewController ()<UITableViewDataSource, UITableViewDelegate, UITextFieldDelegate>
{
    UITableView *_tableView;    //中间表视图
    UIView      *_bottomView;   //底部视图
    
    NSArray *_dataSource; //结算网络data
    
    NSArray *_addressArr;//收货信息用Array
    
    NSString *_aPointStr; /**A账户使用积分*/
    
    NSString *_bPointStr; /**b账户使用积分*/
    
    NSInteger _payType; /** 支付方式 */

    NSArray *_user;//积分数组
}

/**应付多少钱*/
@property (nonatomic,copy) NSString *allPayLabel;
/**应付LAbel*/
@property (nonatomic,strong) UILabel *shouldPayLabel;

/**积分cell*/
@property (nonatomic,strong) ZPayPointsCell *pointCell;
//是否是购物车
@property (strong,nonatomic) NSString *guid;

@end

@implementation ZPayViewController

- (instancetype)initWithArray:(NSArray *)arr
{
    self = [super init];
    if (self) {
        _dataSource = arr[0][@"goods"];
        if (arr[1][@"address"]) {
             _addressArr = @[arr[1][@"address"][@"realname"],arr[1][@"address"][@"mobile"],arr[1][@"address"][@"prov"],arr[1][@"address"][@"dist"],arr[1][@"address"][@"city"],arr[1][@"address"][@"address"],arr[1][@"address"][@"id"]];
        }
        if (!IsNilString(arr[2][@"guid"])) {
            _guid = arr[2][@"guid"];
            _user = arr[3][@"user"];
            [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getAddressData:) name:@"backToAddress" object:nil];
        }else{
        _user = arr[2][@"user"];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getAddressData:) name:@"backToAddress" object:nil];
        }
    }
    return self;
}
#pragma mark *** 从地址返回通知 ***
-(void)getAddressData:(NSNotification *)info{
    NSArray *arr = info.object;
    NSLog(@"fanhulaide ---%@", arr);
    _addressArr = arr;
    [_tableView reloadData];
    
}
#pragma mark - ==== 页面设置 =====
-(void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.titleLb.text = @"结算";
    
    //初始化 中间视图 相关子视图
    [self initSubViews:self.mainMiddleView];
    
    //默认选择 支付宝
    _payType = 0;
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:1];
    [_tableView selectRowAtIndexPath:indexPath animated:YES scrollPosition:UITableViewScrollPositionMiddle];
    
//    ZPayTypeCell *cell = [_tableView cellForRowAtIndexPath:_tableView.indexPathForSelectedRow];
//    cell.pt_iconIV.image = MImage(@"yuang02");
    
}

#pragma mark - 中间视图部分 相关子视图
//初始化子视图
- (void)initSubViews:(UIView *)view {
    //1 顶部线条
    UIImageView *topIV = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, CGRectW(view), 5)];
    [view addSubview:topIV];
    //topIV.backgroundColor = __TestGColor;
    UIImage *image = MImage(@"beijing01");
    //切分图片
//    image = [image resizableImageWithCapInsets:UIEdgeInsetsMake(5, 5, 5, 5) resizingMode:UIImageResizingModeStretch];//拉伸
    image = [image resizableImageWithCapInsets:UIEdgeInsetsMake(5, 5, 5, 5) resizingMode:UIImageResizingModeTile];//平铺
    topIV.image = image;
    
    
    //2 中间表视图
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 5, CGRectW(view), CGRectH(view)-50)];
    [view addSubview:_tableView];
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    //_tableView.backgroundColor = __TestOColor;
    _tableView.dataSource = self;
    _tableView.delegate   = self;
    _tableView.tableHeaderView.backgroundColor = HEXCOLOR(0xffffff);

    //3 底部视图
    _bottomView = [[UIView alloc] initWithFrame:CGRectMake(0, CGRectH(view)-45, CGRectW(view), 45)];
    [view addSubview:_bottomView];
    //_bottomView.backgroundColor = __TestGColor;
    _bottomView.layer.borderWidth = 1.0;
    _bottomView.layer.borderColor = HEXCOLOR(0xdedede).CGColor;
    [self addBottomViewSubViews:_bottomView];//添加底部视图子视图
    
  
}

//添加底部视图子视图
- (void)addBottomViewSubViews:(UIView *)view {
    //左侧视图
    UIView *leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, CGRectW(view)-160, CGRectW(view))];
    [view addSubview:leftView];
    //leftView.backgroundColor = __TestOColor;
    
    //1 支付金额 label
    UILabel *countLb = [[UILabel alloc] initWithFrame:CGRectMake(10, 15, CGRectW(leftView)-20, 20)];
    [leftView addSubview:countLb];
    //countLb.backgroundColor = __TestGColor;
    countLb.font = MFont(14);
    countLb.textColor = __MoneyColor;
    countLb.textAlignment = NSTextAlignmentRight;
    countLb.text = @"应付：￥1178.00";
    _shouldPayLabel = countLb;
    CGFloat allmoney = 0;
    for (int idx = 0; idx<_dataSource.count; idx++) {
        NSDictionary *dic = _dataSource[idx];
        
        allmoney += [dic[@"price_new"] floatValue] * [dic[@"goods_num"] integerValue];
    }
    countLb.text = [NSString stringWithFormat:@"应付：￥%.2f",allmoney];
//    _allPayLabel = countLb;
    _allPayLabel = [NSString stringWithFormat:@"%.2f",allmoney];
    
    //2 运费 label
    UILabel *freightLb = [[UILabel alloc] initWithFrame:CGRectMake(10, CGRectYH(countLb), CGRectW(leftView)-20, 15)];
//    [leftView addSubview:freightLb];
//    freightLb.backgroundColor = __TestOColor;
    freightLb.font = MFont(10);
    freightLb.textColor = HEXCOLOR(0x999999);
    freightLb.textAlignment = NSTextAlignmentRight;
    freightLb.text = @"免运费";
    
    //右侧 支付按钮
    UIButton *payButton = [[UIButton alloc] initWithFrame:CGRectMake(CGRectXW(leftView), 0, 160, CGRectH(view))];
    [view addSubview:payButton];
    payButton.backgroundColor = __DefaultColor;
    payButton.titleLabel.font = MFont(15);
    [payButton setTitle:@"支付" forState:BtnNormal];
    [payButton setTitleColor:HEXCOLOR(0xffffff) forState:BtnNormal];
    [payButton addTarget:self action:@selector(payButtonAciton) forControlEvents:BtnTouchUpInside];

    
}

#pragma mark - ==== 按钮触发方法 =====
- (void)payButtonAciton {
    
    
    NSInteger goodCount = 0;
    NSInteger jifen = 0;
    NSString *cartIdStr = @"";
    for (int idx = 0; idx<_dataSource.count; idx++) {
        NSDictionary *dic = _dataSource[idx];
        goodCount+=[dic[@"goods_num"] integerValue];
        
        
        jifen+=[dic[@"fanli_jifen"] integerValue] *[dic[@"goods_num"] integerValue];
        if ([cartIdStr isEqualToString:@""]) {
            cartIdStr = [NSString stringWithFormat:@"%@",dic[@"cart_id"]];
        }else{
            cartIdStr = [NSString stringWithFormat:@"%@,%@",cartIdStr,dic[@"cart_id"]];
        }
        NSString *userPoint = [NSString stringWithFormat:@"%.2lf",[_allPayLabel floatValue]-[_aPointStr floatValue]-[_bPointStr floatValue]];


    }
    if (IsNilString(_guid)) {
        NSDictionary *paraDic =  @{@"cart_id":cartIdStr,@"address_id":_addressArr.lastObject,@"token":[UdStorage getObjectforKey:Userid]};
            [self posPayWithPara:paraDic];
    }else{
        NSDictionary *paraDic =  @{@"cart_id":cartIdStr,@"address_id":_addressArr.lastObject,@"token":[UdStorage getObjectforKey:Userid],@"guid":_guid,@"goods_num":[NSString stringWithFormat:@"%ld",goodCount]};
            [self posPayWithPara:paraDic];
    }


}
#pragma mark *** 结算并支付 ***
-(void)posPayWithPara:(NSDictionary *)dic{
    
    NSString *title = [NSString stringWithFormat:@"%@商品",simpleTitle];
    CGFloat allpay = 0;
    allpay = [_allPayLabel floatValue]-[_aPointStr floatValue]-[_bPointStr floatValue];
    NSString *price = [NSString stringWithFormat:@"%.2f",allpay];
    for (int idx = 0; idx<_dataSource.count; idx++) {
        NSDictionary *dic = _dataSource[idx];
        title = [NSString stringWithFormat:@"%@%@",title,dic[@"title"]];
    }
    
    [ZHttpRequestService POSTGoods:@"Order/buildOrder" withParameters:dic success:^(id responseObject, BOOL succe, NSDictionary *jsonDic) {
        if (succe) {
            switch (_payType) {
                case 0:
                {
                    NSLog(@"支付宝支付");
                    //支付宝支付
                    [ZPayMoney payWithOrderNumber:jsonDic[@"data"][0] title:title price:price complete:^{
                        //调用后推到首页
                        [self.navigationController popToRootViewControllerAnimated:false];
                        self.tabBarController.selectedIndex = 0;
                    }];
                }
                    break;
                case 1:
                {
                    NSLog(@"微信支付");
                    [ZPayMoney weiXinPayWithOrderNumber:jsonDic[@"data"][0][@"order"] title:[NSString stringWithFormat:@"%@微信支付",simpleTitle] price:price complete:^{
                        [self.navigationController popToRootViewControllerAnimated:false];

                    }];
                }
                    break;
                case 2:
                {
                    NSLog(@"银联支付");
                    //银联
                    [ZPayMoney UnionPayWithOrderNumber:jsonDic[@"data"][0] price:price withVc:self complete:^{
                        //调用后推到首页
                        [self.navigationController popToRootViewControllerAnimated:false];
                        self.tabBarController.selectedIndex = 0;
                    }];
                    
                    
                    
                }
                    break;
                    
                default:
                    break;
            }
            

        }else{
            NSString *message = jsonDic[@"message"];
            [SXLoadingView showAlertHUD:message duration:2];
        }
    } failure:^(NSError *error) {
        
    } animated:YES withView:nil];
}

#pragma mark - ===== tableView DataSource and Delegate =====
//section 4
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 4;
}

//row
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 1) {
        return 3;
    }else if (section == 2){
        if (_dataSource&&_dataSource.count!=0) {
            return _dataSource.count;
        }
        return 0;
    }else {
        return 1;
    }
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    //支付类型
    if (indexPath.section == 1) {
        ZPayTypeCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TypeCell"];
        if (!cell) {
            cell = [[ZPayTypeCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"TypeCell"];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
          }
        NSArray *imas = @[@"zhifubao",@"weixin",@"icon_uppay.png"];
        NSArray *titles = @[@"支付宝",@"微信支付",@"微信支付"];
        NSArray *details = @[@"快捷支付，可支持银行卡支付",@"微信支付",@"银联支付"];
        
        cell.pt_payIV.image = MImage(imas[indexPath.row]);
        cell.pt_titleLb.text = titles[indexPath.row];
        cell.pt_detailLb.text = details[indexPath.row];
        if (indexPath.row==_payType) {
            cell.pt_iconIV.selected = true;
        }else{
            cell.pt_iconIV.selected = false;
        }
        return cell;
    }
    
    //订单信息
    if (indexPath.section == 2) {
        ZPayOrderInfoCell *cell = [tableView dequeueReusableCellWithIdentifier:@"OrderCell"];
        if (!cell) {
            cell = [[ZPayOrderInfoCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"OrderCell"];
            
        }
        
        NSDictionary *dic = _dataSource[indexPath.row];
        cell.cellDetail.text = dic[@"title"];
        [cell.cellImage sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",GoodsImageUrl,dic[@"pic_url"]]]];
        cell.cellRetuPoint.text = [NSString stringWithFormat:@"送：%@分",dic[@"fanli_jifen"]];
        cell.cellPrice.text = [NSString stringWithFormat:@"¥%@",dic[@"price_new"]];
        
        if (dic[@"goods_num"]) {
            cell.cellNumber.text = [NSString stringWithFormat:@"x%@",dic[@"goods_num"]];
            cell.cellAllPrice.text = [NSString stringWithFormat:@"小计：¥%.2lf",[dic[@"price_new"] floatValue] *[dic[@"goods_num"] integerValue]];
        }else{
        cell.cellNumber.text = @"x1";
        cell.cellAllPrice.text = [NSString stringWithFormat:@"小计：¥%.2lf",[dic[@"price_new"] floatValue]];
        }
        NSString *setname = dic[@"taocan_name"];
        if (setname) {
            cell.cellSetName.text = [NSString stringWithFormat:@"套餐：%@",setname];
        }
        //改变颜色和大小
        NSString *text = cell.cellAllPrice.text;
        //NSUInteger length = [text length];
        NSMutableAttributedString *attri = [[NSMutableAttributedString alloc] initWithString:text];
        [attri addAttribute:NSFontAttributeName value:MFont(11) range:NSMakeRange(0, 3)];
        [attri addAttribute:NSForegroundColorAttributeName value:HEXCOLOR(0x999999) range:NSMakeRange(0, 3)];
        [cell.cellAllPrice setAttributedText:attri];
        
        return cell;
    }
    
    //积分
    if (indexPath.section == 3) {
        ZPayPointsCell *cell = [tableView dequeueReusableCellWithIdentifier:@"PointsCell"];
        if (!cell) {
            cell = [[ZPayPointsCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"PointsCell"];
            
        }
        
        self.pointCell = cell;
        cell.pointATX.delegate= self;
        cell.pointATX.tag = ApointTag;
        cell.pointBTX.delegate = self;
        cell.pointBTX.tag = BpointTag;
        NSDictionary *dic = _user[0];

        cell.pointALabel.text = [NSString stringWithFormat:@"A账户：%@",dic[@"add_jf_limit"]];
        cell.pointBLabel.text = [NSString stringWithFormat:@"B账户：%@",dic[@"add_jf_currency"]];
        return cell;
    }
    
    //收货人信息
    ZPayConsigneeInfoCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ConsigneeInfoCell"];
    if (!cell) {
        cell = [[ZPayConsigneeInfoCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"ConsigneeInfoCell"];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }
    cell.consigneeName.text = [NSString stringWithFormat:@"收货人：%@ %@",_addressArr[0],_addressArr[1]];
    cell.consigneeAddress.text = [NSString stringWithFormat:@"%@%@%@%@",_addressArr[2],_addressArr[3],_addressArr[4],_addressArr[5]];
    return cell;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

    
    switch (indexPath.section) {
        case 0:
        {
            NSLog(@"跳转 收货人地址页面");
            ZReceiveAddressViewController *vc = [[ZReceiveAddressViewController alloc] init];
            [self.navigationController pushViewController:vc animated:YES];
        }
            break;
         
        case 1:
        {
            NSLog(@"选择支付方式");
            
            
            for (int idx = 0; idx<3; idx++) {
                if (idx==indexPath.row) {
                    ZPayTypeCell *cell = [tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:idx inSection:1]];
                    cell.pt_iconIV.selected = true;
                    _payType = idx;
                }else{
                    ZPayTypeCell *cell = [tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:idx inSection:1]];
                    cell.pt_iconIV.selected = false;
                }
            }

          
        }
            break;
        default:
            break;
    }


}


- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    switch (indexPath.section) {
        case 1:
        {
//            ZPayTypeCell *cell = [tableView cellForRowAtIndexPath:indexPath];
//            
//            if (indexPath.row) {
//                cell.pt_iconIV.image = MImage(@"yuang01");
//                //_isWeixinPay = YES;
//            }else{
//                cell.pt_iconIV.image = MImage(@"yuang01");
//                //_isWeixinPay = NO;
//            }

        }
            break;
            
        default:
            break;
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, CGRectW(_tableView), 35)];
    headerView.backgroundColor = __TestOColor;

    //1 标题
    UILabel *headerLb = [[UILabel alloc] initWithFrame:CGRectMake(10, 0, CGRectW(headerView)-20, 34)];
    [headerView addSubview:headerLb];
    headerView.backgroundColor = HEXCOLOR(0xffffff);
    headerLb.font = MFont(15);
    headerLb.textColor = HEXCOLOR(0x333333);
    
    
    //2 底线
    UIImageView *lineIV = [[UIImageView alloc] initWithFrame:CGRectMake(0, CGRectH(headerView), CGRectW(headerView), 1)];
    [headerView addSubview:lineIV];
    lineIV.backgroundColor = HEXCOLOR(0xdedede);
    
    if (section == 1) {
        headerLb.text = @"支付方式";
    }else if (section == 2) {
        headerLb.text = @"订单信息";
    }else {
        headerView.hidden = YES;
    }
 
    return headerView;
}


- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    
    UIView *footerView = [[UIView alloc] init];
    
    footerView.backgroundColor = HEXCOLOR(0xdedede);
    return footerView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (section == 1 || section == 2) {
        return 35;
    }
    return 0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 10;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.section == 0) {//收货人信息
        return 70;
    }
    if (indexPath.section == 1) {//选择支付方式
        return 55;
    }
    
    if (indexPath.section == 2) {//订单信息
        return 140;
    }
    
    return 44*5;
}


#pragma mark - 使用积分 textField Delegate
//键盘弹出时 监听键盘高度
- (void)textFieldDidBeginEditing:(UITextField *)textField {
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardShow:) name:UIKeyboardDidShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardHidden:) name:UIKeyboardDidHideNotification object:nil];
}


- (void)textFieldDidEndEditing:(UITextField *)textField {
    
    
    [self.view endEditing:YES];
}

-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{

    return YES;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [self.view endEditing:YES];
    
    if ([textField.text integerValue]<0) {
        [SXLoadingView showAlertHUD:@"积分不能小于0" duration:0.5];
        textField.text = @"0";
        _bPointStr = @"0";
        [self refreshPrice];
        return YES;
        
    }
    
    if (textField.tag == ApointTag) {
        
        if ([textField.text floatValue]>[_user[0][@"add_jf_limit"] floatValue]) {
            [SXLoadingView showAlertHUD:@"大于A账户余额，请重新输入" duration:0.5];
            textField.text = @"0";
            _aPointStr = @"0";
            [self refreshPrice];
            return YES;
        }
      
        _aPointStr = [NSString stringWithFormat:@"%.2f",[textField.text floatValue]];
        
    }
    
    if (textField.tag == BpointTag) {
        
        if ([textField.text floatValue]>[_user[0][@"add_jf_currency"] floatValue]) {
            [SXLoadingView showAlertHUD:@"大于B账户余额，请重新输入" duration:0.5];
             textField.text = @"0";
            _bPointStr = @"0";
            [self refreshPrice];
            return YES;
        }
        _bPointStr = [NSString stringWithFormat:@"%.2f",[textField.text floatValue]];
        
    }
    
    [self refreshPrice];

    return YES;
}
-(void)refreshPrice{
    CGFloat allpay = 0;
    allpay = [_allPayLabel floatValue]-[_aPointStr floatValue]-[_bPointStr floatValue];
    if (allpay<0) {
        if (allpay<0) {
            [SXLoadingView showAlertHUD:@"积分大于价格" duration:0.5];
            self.pointCell.pointATX.text = @"0";
            self.pointCell.pointBTX.text = @"0";
            _bPointStr = @"0";
            _aPointStr = @"0";
            return;
        }
    }
    _shouldPayLabel.text = [NSString stringWithFormat:@"应付：%.2f",allpay];
}

//弹出键盘
- (void)keyboardShow:(NSNotification *)notification {
    //1 获取当前最大Y值
    CGFloat maxY = CGRectGetMaxY(_tableView.frame) + 45;
    //2 获取键盘Y值
    CGRect keyboardFrame = [notification.userInfo[UIKeyboardFrameEndUserInfoKey]CGRectValue];
    CGFloat keybordY = keyboardFrame.origin.y;
//    NSLog(@"当前Y:%lf===键盘Y:%lf",maxY,keybordY);
    //3 计算距离
    CGFloat y = keybordY - maxY;
    if (y < 0) {
        [UIView animateWithDuration:0.25 animations:^{
            self.view.transform = CGAffineTransformMakeTranslation(0, y);
        }];
    }
    
}

//键盘消失
- (void)keyboardHidden:(NSNotification *)notification {
    [UIView animateWithDuration:0.1 animations:^{
        self.view.transform = CGAffineTransformIdentity;
    }];
}

#pragma mark - others
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}

#pragma mark *** 支付 ***
//支付宝支付
-(void)alipayWithDic:(NSString *)orderStr{

    //应用注册scheme,在AlixPayDemo-Info.plist定义URL types
    NSString *appScheme = AlipayScheme;
    
    NSLog(@"orderstr---%@",orderStr);
    //获取的orderstr直接调用支付宝
        [[AlipaySDK defaultService] payOrder:orderStr fromScheme:appScheme callback:^(NSDictionary *resultDic) {
            NSLog(@"reslut = %@",resultDic);
            
            //调用后推到首页
            [self.navigationController popToRootViewControllerAnimated:false];
            self.tabBarController.selectedIndex = 0;
            
        }];
    
}

//微信支付
- (NSString *)jumpToBizPay {
    
    NSLog(@"weixingxin");
    
    if (![WXApi isWXAppInstalled]) {
        [SXLoadingView showAlertHUD:@"未安装微信" duration:0.5];
        return @"未安装微信";
    }
    
    if(![WXApi isWXAppSupportApi]){
        [SXLoadingView showAlertHUD:@"该版本不支持微信支付" duration:0.5];
        return @"该版本不支持微信支付";
    }
    
    //============================================================
    // V3&V4支付流程实现
    // 注意:参数配置请查看服务器端Demo
    // 更新时间：2015年11月20日
    //============================================================
    NSString *urlString   = @"http://wxpay.weixin.qq.com/pub_v2/app/app_pay.php?plat=ios";
    //解析服务端返回json数据
    NSError *error;
    //加载一个NSURL对象
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:urlString]];
    //将请求的url数据放到NSData对象中
    NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
    if ( response != nil) {
        NSMutableDictionary *dict = NULL;
        //IOS5自带解析类NSJSONSerialization从response中解析出数据放到字典中
        dict = [NSJSONSerialization JSONObjectWithData:response options:NSJSONReadingMutableLeaves error:&error];
        
        NSLog(@"url:%@",urlString);
        if(dict != nil){
            NSMutableString *retcode = [dict objectForKey:@"retcode"];
            if (retcode.intValue == 0){
                NSMutableString *stamp  = [dict objectForKey:@"timestamp"];
                
                //调起微信支付
                PayReq* req             = [[PayReq alloc] init];
                req.partnerId           = [dict objectForKey:@"partnerid"];
                req.prepayId            = [dict objectForKey:@"prepayid"];
                req.nonceStr            = [dict objectForKey:@"noncestr"];
                req.timeStamp           = stamp.intValue;
                req.package             = [dict objectForKey:@"package"];
                req.sign                = [dict objectForKey:@"sign"];
                [WXApi sendReq:req];
                //日志输出
                NSLog(@"appid=%@\npartid=%@\nprepayid=%@\nnoncestr=%@\ntimestamp=%ld\npackage=%@\nsign=%@",[dict objectForKey:@"appid"],req.partnerId,req.prepayId,req.nonceStr,(long)req.timeStamp,req.package,req.sign );
                return @"";
            }else{
                return [dict objectForKey:@"retmsg"];
            }
        }else{
            return @"服务器返回错误，未获取到json对象";
        }
    }else{
        return @"服务器返回错误";
    }
}

@end
